import {createRouter, createWebHashHistory} from 'vue-router';
import Home from '@/views/system/Home.vue';
import error from '@/components/Error.vue';
import pinia from '@/stores/index';
import {cosSystem} from '@/stores/system';
const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
  },
  {
    path: '/error',
    name: 'error',
    component: error,
  },
];

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const store = cosSystem();
  if (store.flag == 0 && !hasNecessaryRoute(to)) {
    //try防止接口报错
    try {
      store.flag = 1;
      //添加动态路由
      next({...to, replace: true});
    } catch (e) {
      console.log('获取菜单失败', e);
      // store.flag = 0;
      //获取菜单失败，跳转错误界面
      next('/error');
    }
  } else {
    if (!hasNecessaryRoute(to)) {
      //获取菜单失败，跳转错误界面
      next('/error');
    }
    document.title = to.meta.title;
    next();
  }
});
//判断路由是否存在当前跳转
function hasNecessaryRoute(to) {
  let is = router.getRoutes().filter(route => route.path == to.path).length;
  if (router.hasRoute(to.name) || router.getRoutes().filter(route => route.path == to.path) > 0) {
    return true;
  } else {
    return false;
  }
}

export default router;
